/********************************************************************************
* @file    bsp_pwm.c
* @author  jianqiang.xue
* @version V1.0.0
* @date    2022-02-15
* @brief   NULL
********************************************************************************/

/* Includes ------------------------------------------------------------------*/
#include "RTE_Components.h"
#include CMSIS_device_header

#include "bsp_gpio.h"
#include "bsp_tim.h"
#include "bsp_pwm.h"

/* Private Includes ----------------------------------------------------------*/
#include "ls_gpio.h"
#include "ls_syscfg.h"

/* Private Variables ---------------------------------------------------------*/
static bool g_pwm_init = false;

#if BS_TIM1_EN
extern TMR_TimerBaseInitType tim1_handle_t;
extern TMR_OCInitType tim1_oc_init_handle_t;
#endif

/* Public function prototypes -----------------------------------------------*/
/**
 * @brief  PWN功能初始化，使用定时器来模拟PWM功能
 */
void bsp_pwm_init(void)
{
    if (g_pwm_init)
    {
        return;
    }
#if BS_TIM1_EN
    bsp_tim_pwm_init();
    g_pwm_init = true;
#endif
}

/**
 * @brief  PWN功能关闭
 */
void bsp_pwm_deinit(void)
{
    if (!g_pwm_init)
    {
        return;
    }
#if BS_TIM1_EN
    bsp_tim_pwm_deinit();
    g_pwm_init = false;
#endif
}

/**
 * @brief  设置PWM占空比
 * @param  pwmx: PWM组号
 * @param  val: 0-100 PWM值
 */
void bsp_pwm_set_pulse(bsp_pwm_t pwmx, uint16_t val)
{
    if (!g_pwm_init)
    {
        return;
    }
    if (pwmx == BSP_PWM_0)
    {
#if BS_TIM1_EN && BS_PWM0_EN
        TMR_SetCompare1(TMR1, val);
#endif
    }
    else if (pwmx == BSP_PWM_1)
    {
#if BS_TIM1_EN && BS_PWM1_EN
        TMR_SetCompare2(TMR1, val);
#endif
    }
    else if (pwmx == BSP_PWM_2)
    {
#if BS_TIM1_EN && BS_PWM2_EN
        TMR_SetCompare3(TMR1, val);
#endif
    }
    else if (pwmx == BSP_PWM_3)
    {
#if BS_TIM1_EN && BS_PWM3_EN
        TMR_SetCompare4(TMR1, val);
#endif
    }
}
